package com.sinosoft.call.service.impl;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sinosoft.call.entity.model.CallConfig;
import com.sinosoft.call.service.CallService;
@Service("formCallService")
public class FormCallServiceImpl implements CallService{
	private static Pattern p = Pattern.compile("\\{[^\\{]*\\}");
	@Autowired
	private RestTemplate restTemplate;
	@Override
	public JSONObject callService(CallConfig callConfig, JSON params) {
		MultiValueMap<String, Object> requestParam = new LinkedMultiValueMap<>();
		JSONObject param = (JSONObject) params;

		File file = (File)param.get("files");
	    FileSystemResource resource = new FileSystemResource(file);  
	    requestParam.add("files", resource);
	    param.remove("files");
	    
	    Map<String, Object> uriVariables = new HashMap<>();
	    Set<String> keySet = param.keySet();
		for (String key : keySet) {
			uriVariables.put(key, param.get(key));
		}
		
		String result =  restTemplate.postForObject(callConfig.getCallurl(),requestParam , String.class, uriVariables);
		
		return pubResultJSON(true, "", result);
	}
	
	public Map<String, String> getPathValue(String url, JSONObject param) {
		Map<String, String> re = new HashMap<String, String>();
		Matcher q = p.matcher(url);
		while (q.find()) {
			String key = q.group(0).replaceAll("\\{|\\}", "");
			re.put(key, param.getString(key));
		}
		return re;
	}
}
